--[[
https://www.kyne.com.au/~mark/software/lua-cjson-manual.html

sudo luarocks install lua-cjson
=> /usr/local/lib/luarocks/rocks/lua-cjson/

local cjson = require("cjson")
local tmp1 = cjson.encode(xxtable)
local tmp2 = cjson.decode(tmp1)

--]]

-- CHECK
function isTableEqual(t1, t2)
  assert(type(t1)=='table', 't1 is not a table')
  assert(type(t2)=='table', 't2 is not a table')
  if isTableContain(t1, t2) and isTableContain(t2, t1) then return true end
  return false
end

-- t1 >= t2 ==> t2 is subset of t1
function isTableContain(t1, t2)
  assert(type(t1)=='table', 't1 is not a table')
  assert(type(t2)=='table', 't2 is not a table')

  local flag = true
  for k2, v2 in pairs(t2) do
    -- print('isTableContain, k2='..k2)
    local v1 = t1[k2]
    if not v1 then return false end

    local typeV = type(v2)
    if 'number'== typeV or 'string'== typeV then 
      if v2 ~= v1 then 
        print('not equal,key='..k2)
        return false 
      end 
    elseif 'table' == typeV then return isTableContain(v1, v2)  
    else
      print('======> unknown type='..typeV..',key='..k2)
      return false
    end
  end

  return true
end

local upstream = {
  slb ='rr',
  type ='workflow',
  servers = {
    id1_hash = {
      ip_port ='localhost:8888',
      weight = 1,
      health='ok',
      count_fail = 0,
      count_succ = 123,
      count_pend = 11,
      max_elapse = 1234,
      max_elapse_path ='/foo/bar?token=123'
    },

    id2_hash = {
      p ='localhost:8889',
      weight = 2,
      health ='ok',
      count_fail = 0,
      count_succ = 123,
      count_pend = 11,
      max_elapse = 1234,
      max_elapse_path ='/foo/bar?token=123'
    }
  }
}

-- 
local cjson = require("cjson")
local tmp1 = cjson.encode(upstream)
print(type(tmp1))
print('len=',#tmp1)
local tmp2 = cjson.decode(tmp1)

print("isEqual = ", isTableEqual(upstream, tmp2))
